<template>
  <div class="content-box card" style="position: relative; padding: 0">
    <div class="left-box">
      <div class="title">长者列表</div>
      <div class="elderly-search">
        <div style="padding: 10px">
          <div>
            <el-input
              v-model="elderlyInfoParams.name"
              clearable
              placeholder="请输入长者姓名"
              style="width: 195px; margin-right: 5px"
              size="default"
            />
            <el-select
              v-model="elderlyInfoParams.gender"
              clearable
              placeholder="请选择长者性别"
              style="width: 195px; margin-right: 5px"
              size="default"
            >
              <el-option label="男" :value="1" />
              <el-option label="女" :value="2" />
            </el-select>
            <el-button style="width: 80px" @click="clearSearchParams" icon="Delete" size="default">清空</el-button>
          </div>
          <div style="margin-top: 5px">
            <el-select
              v-model="elderlyInfoParams.mobilityStatus"
              clearable
              placeholder="请选择能力等级"
              style="width: 195px; margin-right: 5px"
              size="default"
            >
              <el-option v-for="item in mobilityStatus" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-select
              v-model="elderlyInfoParams.isSettingCarePlan"
              clearable
              placeholder="是否设置照护计划"
              style="width: 195px; margin-right: 5px"
              size="default"
            >
              <el-option label="未设置" :value="0" />
              <el-option label="已设置" :value="1" />
            </el-select>
            <el-button type="primary" style="width: 80px" @click="loadElderlyList" icon="Filter" size="default">查询</el-button>
          </div>
        </div>
      </div>
      <div class="elderly-plan">
        <div style="padding-right: 10px; padding-left: 10px">
          <div class="elderly-item" v-for="e in elderlyList" :key="e.id">
            <div class="elderly-avatar">
              <el-avatar :size="80" v-if="e.avatarUrl !== ''" :src="e.avatarUrl" />
              <el-avatar :size="80" v-else> {{ e.name }} </el-avatar>
            </div>
            <div class="elderly-info">
              <div style="font-size: 18px; font-weight: 600">{{ e.name }}</div>
              <div class="elderly-detail">
                <div class="detail-item">
                  <span class="detail-item-label">房间号:</span>
                  <span>{{ e.roomNumber }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-item-label">床位号:</span>
                  <span>{{ e.bedNumber }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-item-label">长者年龄:</span>
                  <span>{{ e.age }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-item-label">长者性别:</span>
                  <span>{{ e.genderText }}</span>
                </div>
                <div class="detail-item" style="width: 338px">
                  <span class="detail-item-label">能力等级:</span>
                  <span>{{ getMobilityStatusText(e.mobilityStatus) }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-item-label">照护计划:</span>
                  <span v-if="e.isSettingCarePlan === 1" style="color: var(--el-color-primary-dark-2)">已设置</span>
                  <span v-else>未设置</span>
                </div>
                <div
                  @click="handleSetCarePlan(e)"
                  class="detail-item"
                  style="
                    font-size: var(--el-color-primary);
                    color: var(--el-color-primary);
                    text-align: center;
                    cursor: pointer;
                    background-color: var(--el-color-primary-light-9);
                    border: 1px solid var(--el-color-primary-light-5);
                  "
                >
                  <span>
                    <el-icon style="position: relative; top: 2px; right: 2px"><Edit /></el-icon>设置照护计划
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-empty v-if="elderlyList.length === 0" description="请前往长者资料管理，先维护长者资料" />
      </div>
    </div>
    <div class="right-box">
      <div class="title">长者照护计划详情</div>
      <div class="plan-box">
        <div style="border: 1px solid var(--el-text-color-secondary)">
          <div class="item-box">
            <div class="item" style="margin-bottom: 0">
              <span style="font-size: 18px; font-weight: 600">{{ elderly.name }} 照护计划</span>
            </div>
          </div>
          <div class="item-box">
            <div class="item" style="margin-bottom: 0">
              <div class="col"><span>姓名：</span>{{ elderly.name }}</div>
              <div class="col"><span>性别：</span>{{ elderly.genderText }}</div>
              <div class="col"><span>年龄：</span>{{ elderly.age }}</div>
              <div class="col"><span>能力等级：</span>{{ getMobilityStatusText(elderly.mobilityStatus) }}</div>
              <div class="col"><span>房间号：</span>{{ elderly.roomNumber }}</div>
              <div class="col"><span>床位号：</span>{{ elderly.bedNumber }}</div>
            </div>
          </div>
          <div class="item-box">
            <div class="item">
              <el-input placeholder="这里填写既往史" v-model="elderlyCarePlan.majorMedicalHistory">
                <template #prepend>
                  <div class="til">既往史</div>
                </template>
              </el-input>
            </div>
            <div class="item">
              <el-input placeholder="这里填写过敏史" v-model="elderlyCarePlan.allergies">
                <template #prepend>
                  <div class="til">过敏史</div>
                </template>
              </el-input>
            </div>
            <div class="item">
              <el-input placeholder="这里填写风险防范" v-model="elderlyCarePlan.riskPrevention">
                <template #prepend>
                  <div class="til">风险防范</div>
                </template>
              </el-input>
            </div>
            <div class="item" style="margin-bottom: 0">
              <el-input placeholder="这里填写特殊照护注意事项" v-model="elderlyCarePlan.specialCarePrecautions">
                <template #prepend>
                  <div class="til">特殊照护注意事项</div>
                </template>
              </el-input>
            </div>
          </div>
          <div class="item-box">
            <div class="item" style="margin-bottom: 0">
              <span style="font-size: 18px; font-weight: 600">标准照护计划</span>
              <div
                v-auth="'elderly_care_plan_save'"
                style="position: absolute; top: 50%; left: 120px; transform: translateY(-50%)"
              >
                <el-button icon="Document" type="primary" size="default" @click="openSelectCareTemplateDrawer" plain>
                  选择使用照护模板
                </el-button>
                <el-button icon="Document" type="primary" size="default" @click="openSelectCareMissionDrawer" plain>
                  选择使用照护项目
                </el-button>
              </div>
            </div>
          </div>
          <div class="item-box">
            <div class="item" style="margin-bottom: 0">
              <el-table :data="elderlyCarePlanMission" :span-method="objectSpanMethod" border>
                <el-table-column prop="name" label="时间" width="180" align="center" fixed="left">
                  <template #default="scope">
                    <div v-if="scope.row.isDailyMission">
                      每日：
                      <span v-if="scope.row.dailyMissionStartTime && scope.row.dailyMissionEndTime">
                        {{ scope.row.dailyMissionStartTime }} - {{ scope.row.dailyMissionEndTime }}
                      </span>
                      <span v-else> 不限制时间段 </span>
                    </div>

                    <span v-else> 根据需求及老人情况 </span>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="照护计划项目" width="350" />
                <el-table-column prop="dailyMissionExecutionCount" label="建议执行次数" width="130" align="center">
                  <template #default="scope">
                    <span v-if="scope.row.dailyMissionExecutionCount">{{ scope.row.dailyMissionExecutionCount }} 次</span>
                    <span v-else> -- </span>
                  </template>
                </el-table-column>
                <el-table-column prop="isTakePhotos" label="是否拍照打卡" width="130" align="center">
                  <template #default="scope">
                    <el-switch
                      v-model="scope.row.isTakePhotos"
                      inline-prompt
                      active-text="是"
                      inactive-text="否"
                      @change="changeIsTakePhotos(scope.row)"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="careWorkerEmployeeIdList" label="照护人员" width="300" align="center">
                  <template #default="scope">
                    <el-select v-model="scope.row.careWorkerEmployeeIdList" multiple placeholder="这里选择照护人员">
                      <el-option v-for="item in employeeList" :key="item.id + ''" :label="item.name" :value="item.id + ''" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="注意事项" min-width="500" />
                <el-table-column fixed="right" label="操作" width="140" align="center">
                  <template #default="scope">
                    <el-button
                      v-auth="'elderly_care_plan_save'"
                      link
                      type="primary"
                      size="small"
                      :icon="Edit"
                      @click="editMissionHandle(scope.row)"
                    >
                      编辑
                    </el-button>
                    <el-button
                      v-auth="'elderly_care_plan_save'"
                      link
                      type="danger"
                      size="small"
                      :icon="Delete"
                      @click="removeMissionHandle(scope.row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div class="item-box">
            <div class="item" style="margin-bottom: 0">
              <span style="font-size: 18px; font-weight: 600">个性化照护需求</span>
            </div>
          </div>
          <div class="item-box">
            <div class="item" style="margin-bottom: 0">
              <el-input
                placeholder="这里填写个性化照护需求"
                v-model="elderlyCarePlan.personalizedCareNeeds"
                :rows="6"
                type="textarea"
              >
              </el-input>
            </div>
          </div>
          <div class="item-box" style="border: 0; border-bottom: 0">
            <div class="item" style="margin-bottom: 0">
              <el-button
                type="primary"
                v-auth="'elderly_care_plan_save'"
                :icon="Finished"
                size="default"
                style="width: 175px"
                @click="saveElderlyCarePlanHandle"
              >
                保存照护计划
              </el-button>
              <el-button
                type="danger"
                v-auth="'elderly_care_plan_remove'"
                :icon="Delete"
                size="default"
                style="width: 175px"
                @click="removeElderlyCarePlanHandle"
              >
                删除照护计划
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <SelectCareMissionDrawer ref="selectCareMissionDrawerRef" @change="selectedMissionsChangeCallback" />
    <EditCareMissionDrawer ref="editCareMissionDrawerRef" @change="editMissionChangeCallback" />
    <SelectCarePlanTemplateDrawer ref="selectCarePlanTemplateDrawerRef" @change="selectedTemplateChangeCallback" />
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { Elderly, CareMission, CarePlanTemplate, Employee } from "@/api/interface";
import { getElderlyInfoList } from "@/api/modules/elderly";
import { mobilityStatus } from "@/utils/dict";
import EditCareMissionDrawer from "@/views/care/plan-template/components/EditCareMissionDrawer.vue";
import SelectCareMissionDrawer from "@/views/care/plan-template/components/SelectCareMissionDrawer.vue";
import SelectCarePlanTemplateDrawer from "@/views/care/elderly-plan/components/SelectCarePlanTemplateDrawer.vue";
import { TableColumnCtx, ElMessage, ElMessageBox } from "element-plus";
import { Finished, Delete, Edit } from "@element-plus/icons-vue";
import { getElderlyCarePlanMissionList, saveElderlyCarePlan } from "@/api/modules/elderly";
import { getEmployeeList } from "@/api/modules/employee";

// 老人列表
const elderlyList = ref<Elderly.ResElderlyInfoList[]>([]);
// 选中的老人资料
const elderly = ref<Elderly.ResElderlyInfoList>({ id: 0, name: "", status: 0 });
// 选中的老人照护计划
const elderlyCarePlan = ref<Elderly.ReqSaveElderlyCarePlanInput>({
  elderlyId: 0,
  majorMedicalHistory: "",
  allergies: "",
  riskPrevention: "",
  specialCarePrecautions: "",
  personalizedCareNeeds: "",
  planMissionList: []
});
// 选择老人照护记录动作列表
const elderlyCarePlanMission = ref<Elderly.ElderlyCarePlanMissionDto[]>([]);
// 选择照护项目组件Ref
const selectCareMissionDrawerRef = ref<InstanceType<typeof SelectCareMissionDrawer> | null>(null);
// 编辑照护项目组件Ref
const editCareMissionDrawerRef = ref<InstanceType<typeof EditCareMissionDrawer> | null>(null);
// 选择照护计划模板组件Ref
const selectCarePlanTemplateDrawerRef = ref<InstanceType<typeof SelectCarePlanTemplateDrawer> | null>(null);
// 照护人员列表
const employeeList = ref<Employee.ResEmployeeList[]>([]);

onMounted(async () => {
  await loadElderlyList();
  await loadEmployeeList();
});

// 加载照护人员列表
const loadEmployeeList = async () => {
  const res = await getEmployeeList({ pageNum: 1, pageSize: 9999999 });
  employeeList.value = res.data.list || [];
};

// 照护计划详情
const elderlyInfoParams = ref<Elderly.ReqElderlyInfoParams>({
  pageNum: 1,
  pageSize: 9999999
});

// 加载老人列表
const loadElderlyList = async () => {
  const res = await getElderlyInfoList(elderlyInfoParams.value);
  elderlyList.value = res.data.list || [];

  if (elderlyList.value.length > 0) {
    elderly.value = elderlyList.value[0];
    handleSetCarePlan(elderlyList.value[0]);
  }
};

// 清空查询参数
const clearSearchParams = async () => {
  elderlyInfoParams.value = {
    pageNum: 1,
    pageSize: 9999999,
    name: "",
    gender: undefined,
    mobilityStatus: undefined,
    isSettingCarePlan: undefined
  };
  await loadElderlyList();
};

// 获取能力等级
const getMobilityStatusText = (value?: number) => {
  let obj = mobilityStatus.find(i => i.value === value);
  return obj?.label || "";
};

// 处理设置照护计划
const handleSetCarePlan = async (e: Elderly.ResElderlyInfoList) => {
  elderly.value = e;
  elderlyCarePlan.value.elderlyId = e.id;
  elderlyCarePlan.value.majorMedicalHistory = e.majorMedicalHistory;
  elderlyCarePlan.value.riskPrevention = e.riskPrevention;
  elderlyCarePlan.value.specialCarePrecautions = e.specialCarePrecautions;
  elderlyCarePlan.value.personalizedCareNeeds = e.personalizedCareNeeds;
  elderlyCarePlan.value.allergies = e.allergies;

  // 获取照护计划
  const res = await getElderlyCarePlanMissionList(e.id);

  // 处理照护计划任务列表
  elderlyCarePlan.value.planMissionList = [];
  elderlyCarePlanMission.value = [];

  // 处理照护计划任务列表
  elderlyCarePlanMission.value = res.data || [];
  elderlyCarePlan.value.planMissionList = JSON.parse(JSON.stringify(elderlyCarePlanMission.value));
};

// 打开选择照护项目抽屉
const openSelectCareMissionDrawer = () => {
  if (elderly.value.id == 0) {
    ElMessage("请在左侧长者列表，选择需要设置的长者");
    return;
  }
  selectCareMissionDrawerRef.value?.acceptParams({ drawerVisible: true, title: "选择照护项目" });
};

// 处理选择照护项目事件
const selectedMissionsChangeCallback = (selectedMissions: CareMission.ResCareMission[]) => {
  // 处理显示照护项目列表
  let newElderlyCarePlanMission = JSON.parse(JSON.stringify(elderlyCarePlanMission.value));
  let timestampId: number = Date.now();
  selectedMissions.forEach(m => {
    timestampId = timestampId + 1;
    const mission: Elderly.ElderlyCarePlanMissionDto = {
      id: timestampId,
      categorizeId: m.categorizeId,
      careMissionId: m.id,
      name: m.name,
      description: m.description,
      isDailyMission: m.isDailyMission,
      dailyMissionStartTime: m.dailyMissionStartTime,
      dailyMissionStartTimeValue: m.dailyMissionStartTimeValue,
      dailyMissionEndTime: m.dailyMissionEndTime,
      dailyMissionEndTimeValue: m.dailyMissionEndTimeValue,
      dailyMissionExecutionCount: m.dailyMissionExecutionCount,
      isTakePhotos: false,
      sort: 0,
      isDelete: 0,
      careWorkerEmployeeIdList: elderly.value.careWorkerEmployeeIds || []
    };
    newElderlyCarePlanMission.push(mission);
    // 照护计划任务列表添加任务
    elderlyCarePlan.value.planMissionList.push(JSON.parse(JSON.stringify(mission)));
  });
  newElderlyCarePlanMission = sortMissionList(newElderlyCarePlanMission);
  elderlyCarePlanMission.value = [];
  elderlyCarePlanMission.value = newElderlyCarePlanMission;
};

// 排序照护项目列表
const sortMissionList = (missions: Elderly.ElderlyCarePlanMissionDto[]) => {
  const sortedMissions = missions.sort((a: Elderly.ElderlyCarePlanMissionDto, b: Elderly.ElderlyCarePlanMissionDto) => {
    // 第一优先级：按isDailyMission倒序（1在前，0在后）
    if (a.isDailyMission !== b.isDailyMission) {
      return b.isDailyMission - a.isDailyMission;
    }

    // 第二优先级：按dailyMissionStartTimeValue升序
    // 处理undefined值，将undefined视为最大值排在后面
    if (a.dailyMissionStartTimeValue === undefined && b.dailyMissionStartTimeValue === undefined) {
      return 0;
    }
    if (a.dailyMissionStartTimeValue === undefined) {
      return 1;
    }
    if (b.dailyMissionStartTimeValue === undefined) {
      return -1;
    }

    return a.dailyMissionStartTimeValue - b.dailyMissionStartTimeValue;
  });
  return sortedMissions;
};
// 表格合并行方法
interface SpanMethodProps {
  row: Elderly.ElderlyCarePlanMissionDto;
  column: TableColumnCtx<Elderly.ElderlyCarePlanMissionDto>;
  rowIndex: number;
  columnIndex: number;
}
// 合并行方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  console.log(column);

  if (columnIndex === 0) {
    // 只合并第一列
    // 计算相同时间段的连续行数
    let rowspan = 1;
    for (let i = rowIndex + 1; i < elderlyCarePlanMission.value.length; i++) {
      const current = elderlyCarePlanMission.value[i];
      const prev = elderlyCarePlanMission.value[i - 1];

      if (
        current.dailyMissionStartTimeValue === prev.dailyMissionStartTimeValue &&
        current.dailyMissionEndTimeValue === prev.dailyMissionEndTimeValue &&
        current.isDailyMission === prev.isDailyMission
      ) {
        rowspan++;
      } else {
        break;
      }
    }

    // 如果是合并区域的第一行，返回合并的行数
    if (
      rowIndex === 0 ||
      row.dailyMissionStartTimeValue !== elderlyCarePlanMission.value[rowIndex - 1].dailyMissionStartTimeValue ||
      row.dailyMissionEndTimeValue !== elderlyCarePlanMission.value[rowIndex - 1].dailyMissionEndTimeValue ||
      row.isDailyMission !== elderlyCarePlanMission.value[rowIndex - 1].isDailyMission
    ) {
      return {
        rowspan: rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};

// 编辑照护项目
const editMissionHandle = (row: Elderly.ElderlyCarePlanMissionDto) => {
  const careMission = JSON.parse(JSON.stringify(row)) as CarePlanTemplate.ResCarePlanTemplateMissionDto;
  console.log("编辑照护项目", careMission);
  editCareMissionDrawerRef.value?.acceptParams({ drawerVisible: true, title: "编辑照护项目", row: careMission });
};

// 编辑照护项目回调
const editMissionChangeCallback = (row: CarePlanTemplate.ResCarePlanTemplateMissionDto) => {
  // 查找并更新 detailCareMissionList 中的对应项
  let newElderlyCarePlanMission: Elderly.ElderlyCarePlanMissionDto[] = JSON.parse(JSON.stringify(elderlyCarePlanMission.value));
  for (let i = 0; i < newElderlyCarePlanMission.length; i++) {
    let item = newElderlyCarePlanMission[i];
    if (item.id === row.id) {
      item.id = row.id;
      item.categorizeId = row.categorizeId;
      item.careMissionId = row.careMissionId;
      item.name = row.name;
      item.description = row.description;
      item.isDailyMission = row.isDailyMission;
      item.dailyMissionStartTime = row.dailyMissionStartTime;
      item.dailyMissionStartTimeValue = row.dailyMissionStartTimeValue;
      item.dailyMissionEndTime = row.dailyMissionEndTime;
      item.dailyMissionEndTimeValue = row.dailyMissionEndTimeValue;
      item.dailyMissionExecutionCount = row.dailyMissionExecutionCount;
    }
  }
  newElderlyCarePlanMission = sortMissionList(newElderlyCarePlanMission);
  elderlyCarePlanMission.value = [];
  elderlyCarePlanMission.value = newElderlyCarePlanMission;

  // 查找并更新 detailData.value.missionList 中的对应项
  for (let j = 0; j < elderlyCarePlan.value.planMissionList?.length; j++) {
    let item = elderlyCarePlan.value.planMissionList[j];
    if (item.id === row.id) {
      item.id = row.id;
      item.categorizeId = row.categorizeId;
      item.careMissionId = row.careMissionId;
      item.name = row.name;
      item.description = row.description;
      item.isDailyMission = row.isDailyMission;
      item.dailyMissionStartTime = row.dailyMissionStartTime;
      item.dailyMissionStartTimeValue = row.dailyMissionStartTimeValue;
      item.dailyMissionEndTime = row.dailyMissionEndTime;
      item.dailyMissionEndTimeValue = row.dailyMissionEndTimeValue;
      item.dailyMissionExecutionCount = row.dailyMissionExecutionCount;
    }
  }
};

// 保存照护计划
const saveElderlyCarePlanHandle = async () => {
  if (elderly.value.id == 0) {
    ElMessage("请在左侧长者列表，选择需要设置的长者");
    return;
  }

  // 处理照护人员
  elderlyCarePlanMission.value.forEach(item => {
    elderlyCarePlan.value.planMissionList.forEach(planItem => {
      if (planItem.id === item.id) {
        planItem.careWorkerEmployeeIdList = item.careWorkerEmployeeIdList;
        planItem.careWorkerEmployeeIds = item.careWorkerEmployeeIdList?.join(",");
      }
    });
  });

  // 保存照护计划
  await saveElderlyCarePlan(elderlyCarePlan.value);

  // 更新长者信息
  elderly.value.majorMedicalHistory = elderlyCarePlan.value.majorMedicalHistory;
  elderly.value.riskPrevention = elderlyCarePlan.value.riskPrevention;
  elderly.value.specialCarePrecautions = elderlyCarePlan.value.specialCarePrecautions;
  elderly.value.personalizedCareNeeds = elderlyCarePlan.value.personalizedCareNeeds;
  elderly.value.allergies = elderlyCarePlan.value.allergies;
  ElMessage({
    message: "照护计划保存成功",
    type: "success"
  });

  // 获取照护计划
  const res = await getElderlyCarePlanMissionList(elderlyCarePlan.value.elderlyId);
  elderlyCarePlanMission.value = res.data || [];
  elderlyCarePlan.value.planMissionList = res.data || [];
};

// 选择使用照护计划模板
const openSelectCareTemplateDrawer = () => {
  // 传递参数给抽屉组件
  selectCarePlanTemplateDrawerRef.value?.acceptParams({ drawerVisible: true, title: "选择照护计划模板" });
};

// 删除照护计划项目处理
const removeMissionHandle = (row: Elderly.ElderlyCarePlanMissionDto) => {
  const id = row.id;

  // 处理显示列表数据
  let newElderlyCarePlanMission = JSON.parse(JSON.stringify(elderlyCarePlanMission.value.filter(item => item.id !== id)));
  newElderlyCarePlanMission = sortMissionList(newElderlyCarePlanMission);
  elderlyCarePlanMission.value = [];
  elderlyCarePlanMission.value = newElderlyCarePlanMission;

  // 处理保存列表数据
  for (let i = 0; i < elderlyCarePlan.value.planMissionList.length; i++) {
    if (elderlyCarePlan.value.planMissionList[i].id === id) {
      elderlyCarePlan.value.planMissionList[i].isDelete = 1;
    }
  }
};

// 切换照护项目是否需要拍照
const changeIsTakePhotos = (row: Elderly.ElderlyCarePlanMissionDto) => {
  elderlyCarePlan.value.planMissionList.forEach(item => {
    if (item.id === row.id) {
      item.isTakePhotos = row.isTakePhotos;
    }
  });
};

// 选择照护计划模板回调
const selectedTemplateChangeCallback = (row: CarePlanTemplate.ResCarePlanTemplate) => {
  elderlyCarePlan.value.personalizedCareNeeds = row.personalizedCareNeeds;
  const selectedMissions = row.missionList || [];
  // 处理显示照护项目列表
  let newElderlyCarePlanMission = JSON.parse(JSON.stringify(elderlyCarePlanMission.value));
  let timestampId: number = Date.now();
  selectedMissions.forEach(m => {
    timestampId = timestampId + 1;
    const mission: Elderly.ElderlyCarePlanMissionDto = {
      id: timestampId,
      categorizeId: m.categorizeId,
      careMissionId: m.careMissionId,
      name: m.name,
      description: m.description,
      isDailyMission: m.isDailyMission,
      dailyMissionStartTime: m.dailyMissionStartTime,
      dailyMissionStartTimeValue: m.dailyMissionStartTimeValue,
      dailyMissionEndTime: m.dailyMissionEndTime,
      dailyMissionEndTimeValue: m.dailyMissionEndTimeValue,
      dailyMissionExecutionCount: m.dailyMissionExecutionCount,
      isTakePhotos: false,
      sort: 0,
      isDelete: 0,
      careWorkerEmployeeIdList: elderly.value.careWorkerEmployeeIds || []
    };
    newElderlyCarePlanMission.push(mission);
    // 照护计划任务列表添加任务
    elderlyCarePlan.value.planMissionList.push(JSON.parse(JSON.stringify(mission)));
  });
  newElderlyCarePlanMission = sortMissionList(newElderlyCarePlanMission);
  elderlyCarePlanMission.value = [];
  elderlyCarePlanMission.value = newElderlyCarePlanMission;
};

// 删除照护计划
const removeElderlyCarePlanHandle = async () => {
  if (elderly.value.id == 0) {
    ElMessage("请在左侧长者列表，选择需要删除的长者");
    return;
  }

  // 确认删除
  const confirm = await ElMessageBox.confirm("确认删除照护计划吗？", "删除照护计划", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  });
  if (confirm) {
    elderlyCarePlanMission.value = [];
    elderlyCarePlan.value.planMissionList.forEach(item => {
      item.isDelete = 1;
    });
    elderlyCarePlan.value.personalizedCareNeeds = undefined;
    elderly.value.personalizedCareNeeds = undefined;
    elderly.value.isSettingCarePlan = 0;
    await saveElderlyCarePlan(elderlyCarePlan.value);

    ElMessage({
      message: "照护计划删除成功",
      type: "success"
    });
  }
};
</script>
<style scoped>
.content-box {
  position: relative;
}
.left-box {
  position: absolute;
  top: 0;
  left: 0;
  width: 500px;
  height: 100%;
  border-right: 1px solid var(--el-aside-border-color);
}
.left-box .title {
  height: 55px;
  padding-left: 17px;
  line-height: 55px;
  border-bottom: 1px solid var(--el-aside-border-color);
}
.left-box .elderly-search {
  position: absolute;
  top: 55px;
  right: 0;
  left: 0;
  height: 86px;
  border-bottom: 1px solid var(--el-aside-border-color);
}
.left-box .elderly-plan {
  position: absolute;
  inset: 140px 0 0;
  overflow: auto;
}
.left-box .elderly-plan .elderly-item {
  padding: 10px;
  padding-right: 0;
  margin-top: 10px;
  border: 1px solid var(--el-aside-border-color);
  border-radius: 8px;
}
.left-box .elderly-plan .elderly-item .elderly-avatar {
  position: absolute;
  width: 90px;
  height: 156px;
  border-right: 1px solid var(--el-color-primary-light-9);
}
.left-box .elderly-plan .elderly-item .elderly-info {
  min-height: 80px;
  padding-left: 100px;
}
.left-box .elderly-plan .elderly-item .elderly-info .elderly-detail {
  margin-top: 4px;
}
.left-box .elderly-plan .elderly-item .elderly-info .elderly-detail .detail-item {
  display: inline-block;
  width: 160px;
  padding: 2px 6px;
  margin-right: 5px;
  margin-bottom: 4px;
  background-color: var(--el-color-primary-light-9);
  border-radius: 4px;
}
.left-box .elderly-plan .elderly-item .elderly-info .elderly-detail .detail-item .detail-item-label {
  margin-right: 6px;
  font-size: 16px;
  font-weight: 400;
  color: var(--el-header-text-color-regular);
}
.right-box {
  position: absolute;
  inset: 0 0 0 500px;
}
.right-box .title {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  width: 100%;
  height: 55px;
  padding-left: 17px;
  line-height: 55px;
  border-bottom: 1px solid var(--el-aside-border-color);
}
.right-box .plan-box {
  position: absolute;
  inset: 65px 0 0;
  right: 2px;
  padding: 2px 10px 10px;
  overflow: auto;

  /* border: 1px solid var(--el-text-color-secondary); */
}
.right-box .plan-box .item-box {
  padding: 10px;
  border-bottom: 1px solid var(--el-text-color-secondary);
}
.right-box .plan-box .item-box .item {
  position: relative;
  margin-bottom: 10px;
}
.right-box .plan-box .item-box .item .til {
  width: 115px;
}
.right-box .plan-box .item-box .item .col {
  display: inline-block;
  padding-right: 20px;
  margin-right: 20px;
  border-right: 1px solid var(--el-aside-border-color);
}
</style>
